package com.fin.zw.aiqas.service;

import com.fin.zw.aiqas.entity.QSystemParam;
import com.fin.zw.aiqas.entity.SystemParam;
import com.fin.zw.aiqas.model.request.SystemParamRequest;
import com.fin.zw.aiqas.model.session.SessionModel;
import com.fin.zw.aiqas.repository.SystemParamRepository;
import com.fin.zw.aiqas.util.BadRequestException;
import com.querydsl.core.BooleanBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service("systemParamService")
public class SystemParamService {

    @Autowired
    private SystemParamRepository systemParamRepository;

    /**
     * 系统参数的查询
     *
     * @return
     */
    public Page<SystemParam> querySystemParam(SystemParamRequest request, Pageable pageable) {
        BooleanBuilder builder = new BooleanBuilder();
        QSystemParam qSystemParam = QSystemParam.systemParam;
        if (StringUtils.isNotEmpty(request.getName())) {
            builder.and(qSystemParam.name.eq(request.getName()));
        }
        Page<SystemParam> page = systemParamRepository.findAll(builder, pageable);
        return page;
    }

    /**
     * 系统参数的添加
     *
     * @param request
     */
    public void createSystemParam(SystemParamRequest request, SessionModel sessionModel) {
        SystemParam systemParam = new SystemParam();
        BeanUtils.copyProperties(request, systemParam);
        systemParam.setOperatorId(sessionModel.getUserId());
        systemParam.setOperatorRealName(sessionModel.getUserName());
        systemParam.setCreateTime(new Date());
        systemParamRepository.save(systemParam);
    }

    /**
     * 系统参数的修改
     *
     * @param request
     */
    public void updateSystemParam(SystemParamRequest request) {
        SystemParam systemParam = systemParamRepository.findById(request.getId()).orElseThrow(() -> new BadRequestException("", "修改的系统参数信息不存在！"));
        BeanUtils.copyProperties(request, systemParam);
        systemParamRepository.save(systemParam);
    }

    /**
     * 系统参数的删除
     *
     * @param id
     */
    public void deleteById(Long id) {
        systemParamRepository.deleteById(id);
    }
}
